#pragma once
#include "singleton.h"
#include "MemHandler.h"
#include <map>
#include "msgsn.h"
using namespace std;
namespace cupid
{
class EventMgr:public Singleton<EventMgr>
{
public:
	EventMgr(void){}
	~EventMgr(void){ clear();}
public:
	template<typename T>
	void	registerEvent(int code, T* obj, void ( T::* handler )( MsgSn*));

	void	unregisterEvent(int code);

	void	trigger(int code,MsgSn* sn);

	void	clear();

private:
	map<int,IMemHandler*>	m_handlers;
};

template<typename T>
void EventMgr::registerEvent(int code, T* obj, void ( T::* handler )( MsgSn*))
{
	unregisterEvent(code);
	m_handlers[code] = new MemHandler<T>(obj, handler);
}

inline void EventMgr::unregisterEvent(int code)
{
	map<int,IMemHandler*>::iterator itr = m_handlers.find(code);
	if (itr != m_handlers.end())
	{
		delete itr->second;
		m_handlers.erase(itr);
	}
}

inline void EventMgr::trigger(int code, MsgSn* sn)
{
	map<int,IMemHandler*>::iterator itr = m_handlers.find(code);
	if (itr != m_handlers.end())
	{
		itr->second->execute(sn);
	}
}

inline void EventMgr::clear()
{
	map<int,IMemHandler*>::iterator itr = m_handlers.begin();
	while (itr != m_handlers.end())
	{
		delete itr->second;
		itr++;
	}
	m_handlers.clear();
}

#define sEventMgr cupid::EventMgr::instance()
}